from enum import Enum
from typing import Optional
import logging
import os
from datetime import datetime

class ErrorType(Enum):
    """错误类型枚举"""
    NETWORK_ERROR = "网络错误"  # 网络连接、超时等错误
    API_ERROR = "API错误"  # API调用失败、返回错误等
    PARSE_ERROR = "解析错误"  # 视频信息解析失败
    FILE_ERROR = "文件错误"  # 文件操作相关错误
    GUI_ERROR = "界面错误"  # GUI组件相关错误
    UNKNOWN_ERROR = "未知错误"  # 其他未分类错误

class DownloadError:
    """下载错误信息类"""
    def __init__(self, error_type: ErrorType, message: str, details: Optional[str] = None):
        self.error_type = error_type
        self.message = message
        self.details = details
        self.timestamp = datetime.now()
        self.retry_count = 0
        self.max_retries = 3  # 默认最大重试次数

    def can_retry(self) -> bool:
        """判断是否可以重试"""
        return (
            self.retry_count < self.max_retries
            and self.error_type in [ErrorType.NETWORK_ERROR, ErrorType.API_ERROR]
        )

    def get_recovery_suggestion(self) -> str:
        """获取错误恢复建议"""
        suggestions = {
            ErrorType.NETWORK_ERROR: "请检查网络连接是否正常，稍后重试",
            ErrorType.API_ERROR: "平台API可能存在问题，请稍后重试或检查平台是否正常",
            ErrorType.PARSE_ERROR: "视频信息解析失败，请确认链接是否有效或尝试更新程序",
            ErrorType.FILE_ERROR: "文件操作失败，请检查磁盘空间和文件权限",
            ErrorType.GUI_ERROR: "界面组件出现错误，请尝试重新操作或重启程序",
            ErrorType.UNKNOWN_ERROR: "发生未知错误，请尝试重启程序或报告此问题"
        }
        return suggestions.get(self.error_type, "请稍后重试")

class ErrorLogger:
    """错误日志记录器"""
    def __init__(self):
        self.log_dir = os.path.join(os.path.expanduser("~"), "Downloads", "VideoDownloader", "logs")
        os.makedirs(self.log_dir, exist_ok=True)
        
        self.logger = logging.getLogger("downloader")
        self.logger.setLevel(logging.ERROR)
        
        # 设置日志文件
        log_file = os.path.join(self.log_dir, "error.log")
        handler = logging.FileHandler(log_file, encoding="utf-8")
        handler.setFormatter(
            logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
        )
        self.logger.addHandler(handler)
    
    def log_error(self, error: DownloadError):
        """记录错误信息"""
        error_msg = f"[{error.error_type.value}] {error.message}"
        if error.details:
            error_msg += f"\n详细信息: {error.details}"
        self.logger.error(error_msg)